import React, { useEffect, useState } from 'react';
import { Table, Button, Space, message, Modal, Form, Input, Upload, Image } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { listBanner, updateBanner, deleteBanner, addBanner } from '@/api/bannerController';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd/es/upload';
import type { RcFile } from 'antd/es/upload/interface';
import { withAdminAuth } from '@/components/AdminAuth';

interface BannerData {
  id: string;
  bannerurl: string;
  bannertitle: string;
  createtime: string;
  updatetime: string;
}

const CarouselManagement: React.FC = () => {
  const [bannerList, setBannerList] = useState<BannerData[]>([]);
  const [loading, setLoading] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [currentBanner, setCurrentBanner] = useState<BannerData | null>(null);
  const [uploadLoading, setUploadLoading] = useState(false);
  const [modalType, setModalType] = useState<'edit' | 'add'>('edit');
  const [form] = Form.useForm();

  // 获取轮播图列表
  const fetchBanners = async () => {
    setLoading(true);
    try {
      const res = await listBanner();
      if (res.code === 200) {
        setBannerList(res.data);
      }
    } catch (error) {
      message.error('获取轮播图列表失败');
    }
    setLoading(false);
  };

  useEffect(() => {
    fetchBanners();
  }, []);

  // 处理新增
  const handleAdd = () => {
    setModalType('add');
    form.resetFields();
    setIsModalVisible(true);
  };

  // 处理编辑
  const handleEdit = (record: BannerData) => {
    setModalType('edit');
    setCurrentBanner(record);
    form.setFieldsValue(record);
    setIsModalVisible(true);
  };

  // 处理删除
  const handleDelete = (id: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这张轮播图吗？',
      onOk: async () => {
        try {
          const res = await deleteBanner({ id });
          if (res.code === 200) {
            message.success('删除成功');
            fetchBanners();
          }
        } catch (error) {
          message.error('删除失败');
        }
      }
    });
  };

  // 处理表单提交
  const handleSubmit = async (values: any) => {
    try {
      let res;
      if (modalType === 'edit') {
        res = await updateBanner({
          ...values,
          id: currentBanner?.id,
        });
      } else {
        res = await addBanner(values);
      }

      if (res.code === 200) {
        message.success(modalType === 'edit' ? '更新成功' : '添加成功');
        setIsModalVisible(false);
        fetchBanners();
      }
    } catch (error) {
      message.error(modalType === 'edit' ? '更新失败' : '添加失败');
    }
  };

  // 图片上传相关
  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('只能上传 JPG/PNG 格式的图片!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大小不能超过 2MB!');
    }
    return isJpgOrPng && isLt2M;
  };

  const handleChange: UploadProps['onChange'] = (info) => {
    if (info.file.status === 'uploading') {
      setUploadLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      if (info.file.response.code === 200) {
        setUploadLoading(false);
        const bannerurl = info.file.response.data;
        form.setFieldsValue({ bannerurl });
        message.success('图片上传成功！');
      } else {
        setUploadLoading(false);
        message.error(info.file.response.message || '图片上传失败！');
      }
    }
  };

  const columns: ColumnsType<BannerData> = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 60,
    },
    {
      title: '图片',
      dataIndex: 'bannerurl',
      width: 200,
      render: (bannerurl) => (
        <Image
          src={bannerurl}
          alt="banner"
          width={200}
          height={100}
          style={{ objectFit: 'cover' }}
          preview={{
            maskClassName: 'customize-mask',
            mask: <div>点击查看</div>
          }}
        />
      ),
    },
    {
      title: '标题',
      dataIndex: 'bannertitle',
      width: 200,
    },
    {
      title: '创建时间',
      dataIndex: 'createtime',
      width: 180,
    },
    {
      title: '更新时间',
      dataIndex: 'updatetime',
      width: 180,
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_, record) => (
        <Space size="middle">
          <Button type="link" onClick={() => handleEdit(record)}>编辑</Button>
          <Button type="link" danger onClick={() => handleDelete(record.id)}>删除</Button>
        </Space>
      ),
    },
  ];

  return (
    <div className="p-4">
      <div className="mb-4">
        <Button type="primary" onClick={handleAdd}>
          新增轮播图
        </Button>
      </div>

      <Table 
        columns={columns} 
        dataSource={bannerList}
        rowKey="id"
        loading={loading}
      />

      <Modal
        title={modalType === 'edit' ? '编辑轮播图' : '新增轮播图'}
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
        width={600}
      >
        <Form
          form={form}
          onFinish={handleSubmit}
          layout="vertical"
        >
          <Form.Item label="轮播图" required>
            <Upload
              name="file"
              listType="picture-card"
              showUploadList={false}
              action="http://localhost:8081/api/file/upload"
              beforeUpload={beforeUpload}
              onChange={handleChange}
              data={{ biz: 'banner_image' }}
              withCredentials={true}
            >
              {form.getFieldValue('bannerurl') ? (
                <Image 
                  src={form.getFieldValue('bannerurl')} 
                  alt="banner" 
                  width="100%"
                  height="100%"
                  style={{ objectFit: 'cover' }}
                  preview={{
                    maskClassName: 'customize-mask',
                    mask: <div>点击查看</div>
                  }}
                />
              ) : (
                <div>
                  {uploadLoading ? <LoadingOutlined /> : <PlusOutlined />}
                  <div style={{ marginTop: 8 }}>上传图片</div>
                </div>
              )}
            </Upload>
            <Form.Item name="bannerurl" hidden>
              <Input />
            </Form.Item>
          </Form.Item>

          <Form.Item name="bannertitle" label="标题" rules={[{ required: true }]}>
            <Input />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                保存
              </Button>
              <Button onClick={() => setIsModalVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default withAdminAuth(CarouselManagement); 